<template>
  <div class="page-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="page-search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
          <el-form-item label="科目名称" prop="accountName">
            <el-input v-model="queryParams.accountName" placeholder="请输入科目名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable>
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-btn">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="CirclePlus" @click="handleAdd()" v-hasPermi="['system:account:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-if="refreshTable" :data="accountList" v-loading="loading" row-key="accountId" :default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" class="page-table" border>
        <el-table-column prop="accountName" label="科目名称" header-align="center" />
        <el-table-column prop="accountNo" label="科目代码" align="center" />
        <el-table-column prop="orderNum" label="排序" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:account:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="CirclePlus" @click="handleAdd(scope.row)" v-hasPermi="['system:account:add']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:account:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加或修改科目对话框 -->
      <el-dialog :title="title" v-model="open" append-to-body @close="handleCloseDialog">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :xs="24" :sm="12">
              <el-form-item label="上级科目" prop="parentId">
                <el-tree-select v-model="form.parentId" :data="accountOptions" :props="{ label: 'accountName',  id: 'accountId',  children: 'children' }" node-key="accountId" :default-expanded-keys="defaultExpandedKeys" check-strictly accordion placeholder="选择上级科目" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="科目代码" prop="accountNo">
                <el-input v-model="form.accountNo" placeholder="请输入科目代码" disabled />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="科目名称" prop="accountName">
                <el-input v-model="form.accountName" placeholder="请输入科目名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="负责人" prop="leader">
                <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="科目状态">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark" class="min-rows-2 max-rows-3">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" autosize />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { listAccount, getAccount, delAccount, addAccount, updateAccount, listAccountExcludeChild } from '@/api/system/account';
import { getReimburseNo } from '@/api/common';
import { ComponentInternalInstance } from 'vue';
import { AccountForm, AccountQuery, AccountTree } from '@/api/system/account/types';
import { ElForm } from 'element-plus';
import { recursionLookUpData } from '@/utils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const initForm: AccountForm= {
  accountId: 0,
  parentId: undefined,
  accountNo: '',
  accountName: '',
  orderNum: 0,
  leader: '',
  phone: '',
  email: '',
  status: '0',
  remark: '',
};

const data = reactive<PageData<AccountForm, AccountQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountName: '',
    status: '',
  },
  // 表单校验
  rules: {
    parentId: [
      { required: true, message: '上级科目不能为空', trigger: 'blur' }
    ],
    accountNo: [
      { required: true, message: '科目代码不能为空', trigger: 'blur' }
    ],
    accountName: [
      { required: true, message: '科目名称不能为空', trigger: 'blur' }
    ],
    orderNum: [
      { required: true, message: '显示排序不能为空', trigger: 'blur' }
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      },
    ],
  },
});
const { form, queryParams, rules } = toRefs(data);

// 遮罩层
const loading =  ref<boolean>(true);
// 显示搜索条件
const showSearch = ref<boolean>(true);
// 表格树数据
const accountList = ref<AccountTree[]>([]);
// 科目树选项
const accountOptions = ref<any[]>([]);
// 弹出层标题
const title = ref<string>('');
// 是否显示弹出层
const open = ref<boolean>(false);
// 是否展开，默认全部展开
const isExpandAll = ref<boolean>(true);
// 重新渲染表格状态
const refreshTable = ref<boolean>(true);


/** 查询科目列表 */
const getList = () => {
  loading.value = true;
  listAccount(queryParams.value).then(response => {
    accountList.value = proxy?.handleTree(response.data, 'accountId') as AccountTree[];
    loading.value = false;
  });
};
getList();
/** 转换科目数据结构 */
// const normalizer = (node: AccountTree) => {
//   if (node.children && !node.children.length) {
//     delete node.children;
//   }
//   return {
//     id: node.accountId,
//     label: node.accountName,
//     children: node.children
//   };
// };
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};
// 表单重置
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const reset = () => {
  form.value = { ...initForm };
  formRef.value?.resetFields();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const queryFormRef = ref<InstanceType<typeof ElForm> | null>(null);
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 获取报销单号 */
const getAccountNo = () => {
  const params = { businessType: 'SN_ACCOUNT_BH' };
  return getReimburseNo(params);
};
/** 新增按钮操作 */
const handleAdd = (row?: any) => {
  open.value = true;
  title.value = '添加科目';
  nextTick(() => {
    reset();
    if (row) {
      form.value.parentId = row.accountId;
    }
    Promise.all([listAccount(), getAccountNo()]).then(resList => {
      const list: AccountTree[] = proxy?.handleTree(resList[0].data, 'accountId') as AccountTree[];
      accountOptions.value = row ? list : [{ accountId: list[0].parentId, accountName: '报账科目', children: list }];
      form.value.accountNo = resList[1].data || '';
    });
  });
};
/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};
/** 修改按钮操作 */
const defaultExpandedKeys = ref<string[]>([]);
const handleUpdate = (row: any) => {
  reset();
  getAccount(row.accountId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = '修改科目';
    listAccountExcludeChild(row.accountId).then(response => {
      const list = proxy?.handleTree(response.data, 'accountId') as AccountTree[];
      if (list.length == 0) {
        const noResultsOptions: AccountTree = { accountId: form.value.parentId as number, accountName: form.value.parentName as string, children: [] };
        list.push(noResultsOptions);
      };
      accountOptions.value = [{ accountName: '报账科目', accountId: 0, children: list }];
      const res: string[] = [];
      const keys = recursionLookUpData(accountOptions.value, (v) => v.accountId === form.value.parentId , 'accountId', res);
      defaultExpandedKeys.value = keys.slice(0, keys.length - 1);
    });
  });
};

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.value.accountId) {
        updateAccount(form.value).then(() => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        if (form.value.accountId === 0) {
          delete form.value.accountId;
        }
        addAccount(form.value).then(() => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  proxy?.$modal.confirm('是否确认删除名称为"' + row.accountName + '"的数据项？').then(function() {
    return delAccount(row.accountId);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }).catch(() => {});
};
/** 关闭弹窗回调 */
const handleCloseDialog = () => {
  defaultExpandedKeys.value = [];
};
</script>
